package com.mgq.juc.cas;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * AtomicReference 无法解决A-B-A问题
 * 使用AtomicStampReference来解决 A-B-A
 */
@Slf4j
public class TestAtomicStampReference {
    //初始stamp为0
    static AtomicStampedReference<String> stampedReference = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) throws InterruptedException {
        int stamp = stampedReference.getStamp();
        change();
        Thread.sleep(1000);
        boolean b = stampedReference.compareAndSet("A", "C", stamp, stamp + 1);
        //stamp发生了变化,无法修改
        log.debug(String.valueOf(b));

    }

    private static void change() {
        new Thread(()->{
            int stamp = stampedReference.getStamp();
            boolean b = stampedReference.compareAndSet("A", "B", stamp,stamp + 1);
            log.debug(String.valueOf(b));
        },"t1").start();
        new Thread(()->{
            int stamp = stampedReference.getStamp();
            boolean b = stampedReference.compareAndSet("B", "A", stamp,stamp + 1);
            log.debug(String.valueOf(b));
        },"t2").start();
    }
}
